"""
审核工作进程
"""
import json
import time
import threading
from typing import Optional
from datetime import datetime
from config.settings import settings
from utils.logger import audit_logger
from services.redis_client import redis_client
from models.schemas import AuditRequest, AuditResponse
from core.audit_engine import audit_engine
from database.audit_dao import audit_dao
from monitoring.metrics import metrics_collector


class AuditWorker:
    """审核工作进程"""
    
    def __init__(self):
        self.is_running = False
        self.worker_thread = None
        self.processed_count = 0
        self.error_count = 0
        self.start_time = None
    
    def start(self):
        """启动工作进程"""
        if self.is_running:
            audit_logger.warning("审核工作进程已在运行")
            return
        
        self.is_running = True
        self.start_time = datetime.now()
        self.worker_thread = threading.Thread(target=self._worker_loop, daemon=True)
        self.worker_thread.start()
        
        audit_logger.info("审核工作进程已启动")
    
    def stop(self):
        """停止工作进程"""
        if not self.is_running:
            return
        
        self.is_running = False
        if self.worker_thread:
            self.worker_thread.join(timeout=5)
        
        audit_logger.info("审核工作进程已停止")
    
    def _worker_loop(self):
        """工作循环"""
        audit_logger.info("开始监听审核队列...")
        
        while self.is_running:
            try:
                # 更新队列长度监控
                queue_length = redis_client.get_queue_length(settings.audit_queue_name)
                metrics_collector.update_queue_length(settings.audit_queue_name, queue_length)

                # 从队列获取审核请求
                request_data = redis_client.pop_from_queue(
                    settings.audit_queue_name,
                    timeout=1  # 1秒超时，避免阻塞太久
                )

                if request_data is None:
                    continue
                
                # 处理审核请求
                self._process_audit_request(request_data)
                
            except Exception as e:
                audit_logger.error(f"工作循环异常: {e}")
                self.error_count += 1
                time.sleep(1)  # 出错后短暂休息
    
    def _process_audit_request(self, request_data: dict):
        """处理审核请求"""
        try:
            # 解析请求数据
            audit_request = self._parse_request(request_data)
            if audit_request is None:
                return
            
            audit_logger.info(f"处理审核请求: 帖子ID {audit_request.post_id}")
            
            # 执行审核
            audit_response = audit_engine.audit_content(audit_request)

            # 保存审核记录到数据库
            audit_dao.save_audit_record(audit_response)

            # 更新每日统计
            audit_dao.update_daily_statistics(audit_response)

            # 发送审核结果
            self._send_audit_result(audit_response)

            # 更新统计
            self.processed_count += 1
            
            audit_logger.info(f"审核请求处理完成: 帖子ID {audit_request.post_id}, 结果: {audit_response.audit_result}")
            
        except Exception as e:
            audit_logger.error(f"处理审核请求失败: {e}")
            self.error_count += 1
    
    def _parse_request(self, request_data: dict) -> Optional[AuditRequest]:
        """解析审核请求"""
        try:
            # 调试：打印接收到的原始数据
            audit_logger.info(f"接收到审核请求数据: {request_data}")

            # 验证必需字段
            required_fields = ['post_id', 'content', 'author_id']
            for field in required_fields:
                if field not in request_data:
                    audit_logger.error(f"审核请求缺少必需字段: {field}")
                    return None

            # 解析时间戳，处理不同格式
            timestamp_str = request_data.get('timestamp', datetime.now().isoformat())
            try:
                # 处理带Z后缀的ISO格式
                if timestamp_str.endswith('Z'):
                    timestamp_str = timestamp_str[:-1] + '+00:00'
                timestamp = datetime.fromisoformat(timestamp_str)
            except ValueError:
                # 如果解析失败，使用当前时间
                audit_logger.warning(f"时间戳格式无效，使用当前时间: {timestamp_str}")
                timestamp = datetime.now()

            # 处理images字段，确保是字符串列表
            images_data = request_data.get('images', [])
            images = []

            if images_data and isinstance(images_data, list):
                # 检查是否是Java序列化格式 ['java.util.ArrayList', [actual_data]]
                if len(images_data) == 2 and isinstance(images_data[0], str) and 'java.util.' in images_data[0]:
                    # 提取实际的图片列表
                    actual_images = images_data[1] if isinstance(images_data[1], list) else []
                    images = [img for img in actual_images if img and isinstance(img, str) and img.strip() and not img.startswith('java.')]
                elif isinstance(images_data[0], list):
                    # 展平嵌套列表
                    images = [img for sublist in images_data for img in sublist if img and isinstance(img, str) and img.strip()]
                else:
                    # 过滤空字符串和Java类型信息
                    images = [img for img in images_data if img and isinstance(img, str) and img.strip() and not img.startswith('java.')]

            audit_logger.info(f"处理后的图片列表: {images}")

            # 创建审核请求对象
            audit_request = AuditRequest(
                post_id=request_data['post_id'],
                content=request_data['content'],
                title=request_data.get('title'),
                images=images,
                author_id=request_data['author_id'],
                timestamp=timestamp
            )

            return audit_request

        except Exception as e:
            audit_logger.error(f"解析审核请求失败: {e}")
            return None
    
    def _send_audit_result(self, audit_response: AuditResponse):
        """发送审核结果"""
        try:
            # 转换为字典
            result_data = {
                'post_id': audit_response.post_id,
                'audit_result': audit_response.audit_result.value,
                'confidence': audit_response.confidence,
                'reasons': audit_response.reasons,
                'details': audit_response.details,
                'processed_at': audit_response.processed_at.isoformat()
            }
            
            # 发送到结果队列
            success = redis_client.push_to_queue(settings.result_queue_name, result_data)
            
            if success:
                audit_logger.debug(f"审核结果已发送: 帖子ID {audit_response.post_id}")
            else:
                audit_logger.error(f"发送审核结果失败: 帖子ID {audit_response.post_id}")
                
        except Exception as e:
            audit_logger.error(f"发送审核结果异常: {e}")
    
    def get_status(self) -> dict:
        """获取工作进程状态"""
        uptime = (datetime.now() - self.start_time).total_seconds() if self.start_time else 0
        
        return {
            'is_running': self.is_running,
            'processed_count': self.processed_count,
            'error_count': self.error_count,
            'uptime_seconds': uptime,
            'queue_length': redis_client.get_queue_length(settings.audit_queue_name),
            'result_queue_length': redis_client.get_queue_length(settings.result_queue_name)
        }
    
    def reset_statistics(self):
        """重置统计信息"""
        self.processed_count = 0
        self.error_count = 0
        self.start_time = datetime.now()
        audit_logger.info("工作进程统计信息已重置")


# 全局审核工作进程实例
audit_worker = AuditWorker()
